const { app, BrowserWindow, ipcMain, dialog, globalShortcut, Menu } = require('electron')
const path = require('node:path')
const WinState = require('electron-win-state').default
const menuTemplate = require('./mainMenu')

const menu = Menu.buildFromTemplate(menuTemplate)
Menu.setApplicationMenu(menu)

const winState = new WinState({})
const createWindows = () => {
  const win = new BrowserWindow({
    width: 1280,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      preload: path.join(__dirname, 'preLoad.js'),
    },
    ...winState.winOptions,
  })

  win.loadFile('index.html')

  win.webContents.openDevTools()

  winState.manage(win)

  globalShortcut.register('Ctrl+g', () => {
    console.log('gggggg')
  })
}

app.whenReady().then(() => {
  createWindows()
  // 仅 macOS 支持
  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindows()
    }
  })
})

app.on('window-all-closed', () => {
  // 对于 Mac 系统， 关闭窗口时并不会直接退出应用， 此时需要我们来手动处理
  if (process.platform === 'darwin') {
    console.log('close')
    app.quit()
  }
})

ipcMain.handle('msg-dialog', (event, data) => {
  dialog
    .showMessageBox({
      type: 'question',
      buttons: ['好的', '取消'],
      title: 'Confirm',
      message: data,
    })
    .then((res) => {
      console.log(res)
    })
})

ipcMain.handle('file-dialog', (event, data) => {
  dialog
    .showOpenDialog({
      buttonLabel: '选择',
      defaultPath: app.getPath('desktop'),
      properties: [
        'multiSelections',
        'createDirectory',
        'openFile',
        'openDirectory',
      ],
    })
    .then((res) => {
      console.log(res)
    })
})

ipcMain.handle('save-file-dialog', (event, data) => {
  dialog.showSaveDialog({
    defaultPath: app.getPath('desktop'),
  }).then((res) => {
    console.log(res)
  })
})

ipcMain.handle('error-dialog', (event, data) => {
  dialog.showErrorBox('错误', data)
})
